package botcraft.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Configuration {
	private static final Logger logger = Logger.getLogger(Configuration.class.getName());
	private static final String DEFAULT_CONFIGURATION = "configuration.properties";
	private static final String USER_CONFIGURATION = System.getProperty("user.home") + File.separator + ".botcraft.properties";
	private static final String CONFIGURATION_COMMENTS = "Botcraft Configuration File";
	
	private static Properties configuration = new Properties();
	
	public static Properties loadConfiguration() {
		try {
			loadConfiguration(Configuration.class.getResourceAsStream(DEFAULT_CONFIGURATION));
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Error loading defautl configuration", e);
		}
		File userConfiguration = new File(USER_CONFIGURATION);
		if (userConfiguration.exists()) {
			try {
				loadConfiguration(new FileInputStream(USER_CONFIGURATION));
			} catch (IOException e) {
				logger.log(Level.WARNING, "Error loading user configuration", e);
			}
		}
		return configuration;
	}
	
	public static Properties loadConfiguration(final File file) {
		loadConfiguration();
		try {
			loadConfiguration(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			logger.log(Level.WARNING, "Error configuration from file " + file, e);
		} catch (IOException e) {
			logger.log(Level.WARNING, "Error configuration from file " + file, e);
		}
		return configuration;
	}
	
	public static void saveConfiguration() throws FileNotFoundException, IOException {
		saveConfiguration(new FileOutputStream(USER_CONFIGURATION));
	}
	
	public static void saveConfiguration(final File file) throws FileNotFoundException, IOException {
		saveConfiguration(new FileOutputStream(file));
	}
		
	private static void loadConfiguration(final InputStream input) throws IOException {
		configuration = new Properties();
		configuration.load(input);
		input.close();	
	}
	
	private static void saveConfiguration(final OutputStream output) throws IOException {
		configuration.store(output, CONFIGURATION_COMMENTS);
		output.close();
	}
}
